<?php
/**
* 数据库连接类
*
* Copyright(c) 2012 by Tony. All rights reserved
* To contact the author write to {@link mailto:taonzy@163.com}
* @author Tony
*/
class DB {
    //PDO对象
    private $pdo = null;
    static private $instance = null;       //用于存放实例化的对象
    //公共静态方法获取实例化的对象
    static protected function getInstance() {
        if(!(self::$instance instanceof self)){
            self::$instance = new self();
        }
        return self::$instance;
    }
    //私有克隆
    private function __clone() {
    }
    private function __construct() {
        try{
            $this->pdo = new PDO(DB_DNS,DB_USER,DB_PASSWD,array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES '.DB_CHARSET));
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }catch (PDOException $e){
            die('deny access to database!'.$e->getMessage());
        }
    }
    protected function add($tables,$addData) {
        $addData = Tool::setFormString($addData);
        $addFields = array();
        $addValues = array();
        foreach ($addData as $key=>$value){
            $addFields[] = $key;
            $addValues[] = $value;
        }
        $addFields = implode(',',$addFields);
        $addValues = implode("','",$addValues);
        $sql = "INSERT INTO {$tables[0]} ($addFields) VALUES ('$addValues')";
        //var_dump($sql);die();
        return $this->execute($sql)->rowCount();
    }
	protected function isOne($tables,Array $param) {
		$where = '';
		foreach ($param as $key=>$value) {
			$where .= $value . ' AND ';
		}
		$where = 'WHERE ' . substr($where, 0, -4);
		$sql = "SELECT id FROM {$tables[0]} {$where} LIMIT 1";
        //var_dump($sql);die();
		return $this->execute($sql)->rowCount();
	}
    //查询
    protected function select($tables,Array $fields,Array $param = array()) {
        $limit = $order = $where = '';
        if(!Validate::isNullArray($param)){
            $limit = isset($param['limit']) ? 'LIMIT '.$param['limit'] : '';
            $order = isset($param['order']) ? 'ORDER BY '.$param['order'] : '';
            if(isset($param['where']) && Validate::isArray($param['where'])){
		        foreach ($param['where'] as $key=>$value) {
			        $where .= $value . ' AND ';
		        }
		        $where = 'WHERE ' . substr($where, 0, -4);
            }
        }
        $selectFields = implode(',',$fields);
        $table = isset($tables[1]) ? $tables[0].','.$tables[1] : $tables[0];
        $sql = "SELECT {$selectFields} FROM {$table} {$where} {$order} {$limit}";
        //var_dump($sql);die();
        $stmt = $this->execute($sql);
        $result = array();
        while(!!$objs = $stmt->fetchObject()){
            $result[] = $objs;
        }
        return Tool::setHtmlString($result);
    }
    protected function login($tables,$fields,Array $param) {
        if(!Validate::isNullArray($param)){
            $where = '';
		    foreach ($param['where'] as $key=>$value) {
			    $where .= $value . ' AND ';
		    }
		    $where = 'WHERE ' . substr($where, 0, -4);
            $selectFields = implode(',',$fields);
            $sql = "SELECT {$selectFields} FROM {$tables[0]} {$where} LIMIT 1";
            //var_dump($sql);die();
            $result = $this->execute($sql)->fetchObject();
            return Tool::setHtmlString($result);
        }
    }
    //删除
    protected function del($tables,Array $param) {
        $where = '';
		foreach ($param as $key=>$value) {
			$where .= $value . ' AND ';
		}
		$where = 'WHERE ' . substr($where, 0, -4);
        $sql = "DELETE FROM {$tables[0]} {$where} LIMIT 1";
        //var_dump($sql);die();
        return $this->execute($sql)->rowCount();
    }
    //更新
    protected function update($tables,Array $param,Array $updateData) {
        $where = '';
		foreach ($param as $key=>$value) {
			$where .= $value . ' AND ';
		}
		$where = 'WHERE ' . substr($where, 0, -4);
        $setData = '';
        foreach ($updateData as $key=>$value) {
            if(Validate::isArray($value)){
                $setData .="$key = $value[0],";
            }else{
                $setData .= "$key='$value',";
            }
		}
        $setData = substr($setData, 0, -1);
        $sql = "UPDATE {$tables[0]} SET {$setData} {$where} LIMIT 1";
        //var_dump($sql);die();
        //var_dump($this->execute($sql)->rowCount());die();
        return $this->execute($sql);
    }
    //数据总记录数
    protected function total($tables,$param = array()) {
        $where = '';
		if (isset($param['where'])) {
			foreach ($param['where'] as $key=>$value) {
				$where .= $value . ' AND ';
			}
			$where = 'WHERE ' . substr($where, 0, -4);
		}
        $sql = "SELECT COUNT(id) AS count FROM {$tables[0]} $where";
        //var_dump($sql);die();
        return $this->execute($sql)->fetchObject()->count;
    }
    //得到下一个ID
	protected function nextId($tables) {
		$sql = "SHOW TABLE STATUS LIKE '{$tables[0]}'";
		return $this->execute($sql)->fetchObject()->Auto_increment;
	}
    /*
     * 获取表的所有字段
     * @return array
     */
    protected function list_tables($tables){
        $sql = "select COLUMN_NAME from information_schema.columns where table_name='".$tables[0]."'";
        $result = array();
        foreach ($this->execute($sql) as $key => $value) {
            $result[] = $value['COLUMN_NAME'];
        }
        return $result;
    }
    //执行sql
	private function execute($sql) {
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute();
        } catch (PDOException $e){
            die('SQL Statement:'.$sql.'<br/>ERROR:'.$e->getMessage());
        }
		return $stmt;
	}
}